package com.zys.filter;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域请求的过滤器
 */
public class SimpleCORSFilter implements Filter {
  private boolean isCross = false;

  @Override
  public void destroy() {
    isCross = false;
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws ServletException, IOException {
    if (isCross) {
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;
      httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
      httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
      httpServletResponse.setHeader("Access-Control-Max-Age", "0");
      httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
      httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
    }

    chain.doFilter(request, response);
  }

  @Override
  public void init(FilterConfig filterConfig) {
    String isCrossStr = filterConfig.getInitParameter("IsCross");
    isCross = isCrossStr.equals("true");
  }

}